package Servlet;

import Bean.Employee;
import Utils.DateConvertor;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;

@WebServlet("/emp")
public class ServletEmployee extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("application/json;charset=UTF-8");
		//现在的需求额就是前端传过来employee的参数，
		//后端就是将参数封装程一个employee对象，然后再将这个对象给传过去

		//进行跨域请求
		resp.setHeader("Access-Control-Allow-Origin","*");
		//将得到的请求放在一个map中
		Map<String, String[]> parameterMap = req.getParameterMap();


		Employee employee=new Employee();
		//注册一个转换器，告诉DateConveter该怎么进行转换
		ConvertUtils.register(new DateConvertor("yyyy-MM-dd"),Date.class);
		try {
			BeanUtils.populate(employee,parameterMap);
			//这里不使用这个api的话，
			//先接收参数，然后再将这个的参数给employee的属性进行赋值，
			//如何赋值呢?通过反射，得到一个类的对象，在进行拼接方法，通过调用set方法，再进行赋值
		} catch (Exception e) {
			e.printStackTrace();
		}
		//System.out.println(employee);
		//响应json数据
		//Employee employee=new Employee(1001,"张三","会计",new Date(),8000.0,60);
		String jsonStr= JSONObject.toJSONString(employee);
		resp.getWriter().write(jsonStr);
		System.out.println(jsonStr);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req,resp);
	}
}
